/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';

type FormDataType = {
  mode: string;
  surface: pickedFaceData;
  point?: pickedVertexData;
  offset?: number;
};

type Params = {
  mode: string;
  surface: string;
  point?: string;
  offset: number;
};

function SurfaceDialog({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData: FormDataType = {
    mode: 'distance',
    surface: null,
    point: null,
    offset: 0,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  const { picker } = useTools();

  const execute = (preview: boolean) => {
    const { surface, offset, mode, point } = formData;

    const params: Params = {
      mode: mode,
      point: point?.vertexId,
      surface: surface.meshId,
      offset: offset,
    };

    return confirmCommand(
      {
        type: 'Offset',
        a: {
          ...params,
        },
      },
      preview,
    );
  };

  useEffect(() => {
    preview();
  }, [formData]);

  const isFormDataValid = () => {
    const { surface, point, offset } = formData;

    return (surface != null || point != null) && offset != null;
  };

  const preview = async () => {
    clear();
    if (!isFormDataValid()) {
      return;
    }

    await execute(true);
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear } = useCommand(
    'cmd-offset-curved',
    {
      commandName: 'CreateSurface',
      dependencies: props?.params
        ? [
            props.params.surface?.split(':')[0],
            props.params.point?.split(':')[0],
          ]
        : [],
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    },
  );

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { surface, offset, mode, point } = params;
    await initEditDependency([surface, point]);
    setFormData({
      mode: mode,
      surface: picker.generatePickObjByPickID(surface) as pickedFaceData,
      point: picker.generatePickObjByPickID(point) as pickedVertexData,
      offset,
    });
  }, []);

  const schema: RJSFSchema = useMemo(() => {
    const properties =
      formData.mode === 'distance'
        ? {}
        : {
            point: {
              type: 'string',
              format: PickInputRJSFFormat.PickVertex,
            },
          };

    return {
      type: 'object',
      properties: {
        mode: {
          title: '偏移类型',
          type: 'string',
          oneOf: [
            {
              type: 'string',
              title: '按距离',
              const: 'distance',
            },
            {
              type: 'string',
              title: '直到点',
              const: 'point',
            },
          ],
          default: 'distance',
        },
        surface: {
          type: 'string',
          format: PickInputRJSFFormat.PickSurface,
        },
        ...properties,
        offset: {
          type: 'number',
          title: '偏移',
          default: 0,
          format: NumberInputFormat.Length,
        },
      },
    } as RJSFSchema;
  }, [formData.mode]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      isFormDataValid={isFormDataValid()}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        surface: {
          'ui:placeholder': '请输入曲面',
          'ui:autofocus': true,
        },
        point: {
          'ui:placeholder': '请输入点',
          'ui:autofocus': true,
        },
        offset: {
          'ui:placeholder': '请输入偏移量',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}

export const cmdSurfaceTranslation: CurvedBaseCommand = {
  id: 'CmdSurfaceTranslation',
  label: 'command.surface-translation',
  icon: 'commands/curved/surface-translation',
  create: (label: string, onClose: () => void, props: any) => (
    <SurfaceDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
